package com.seeyon.apps.reimburseplugin.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;







public class HttpUtils {
	private static final Log logger=LogFactory.getLog(HttpUtils.class);


	public String httpPost(String serverURL,String json) {
			HttpURLConnection connection = null;
			OutputStream dataout = null;
			BufferedReader reader = null;
			String line = null;
			try {
				  URL url = new URL(serverURL);
			      connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
			      connection.setDoOutput(true);// 设置是否向connection输出，因为这个是post请求，参数要放在http正文内，因此需要设为true,默认情况下是false
			      connection.setDoInput(true); // 设置是否从connection读入，默认情况下是true;
		          connection.setRequestMethod("POST");// 设置请求方式为post,默认GET请求
			      connection.setUseCaches(false);// post请求不能使用缓存设为false
		          connection.setConnectTimeout(3000);// 连接主机的超时时间                                                                                                                                                      
		          connection.setReadTimeout(3000);// 从主机读取数据的超时时间
		          connection.setInstanceFollowRedirects(true);// 设置该HttpURLConnection实例是否自动执行重定向
			      connection.setRequestProperty("connection", "Keep-Alive");// 连接复用
			      
			      connection.setRequestProperty("charset", "utf-8");
			      
		          connection.setRequestProperty("Content-Type", "application/json");
			      connection.setRequestProperty("Authorization", "Bearer 66cb225f1c3ff0ddfdae31rae2b57488aadfb8b5e7");
			      connection.connect();// 建立TCP连接,getOutputStream会隐含的进行connect,所以此处可以不要                                                                                                                                                                                                                      
		 
			      dataout = new DataOutputStream(connection.getOutputStream());// 创建输入输出流,用于往连接里面输出携带的参数
			      logger.info("==========111111");
			      dataout.write(json.getBytes("utf-8"));
			      dataout.flush();
			      dataout.close();
			      logger.info("==========222222,responseCode:"+connection.getResponseCode());
			      
			      if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
			         reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
			         StringBuilder result = new StringBuilder();
			           // 循环读取流
			         while ((line = reader.readLine()) != null) {
			              result.append(line).append(System.getProperty("line.separator"));//
			          }
			         logger.info("=======result:"+result.toString());
		             System.out.println(result.toString());
		             JSONObject subObj=JSONObject.parseObject(result.toString());
		             String code=subObj.getString("code");
		             return code;
			       }
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("httpPost error:",e);
		} finally {
           try {
        	   if(reader != null) {
        		   reader.close();
        	   }
	          } catch (IOException e) {
	              e.printStackTrace();
	          }
	           connection.disconnect();
	           
		}
			return null;


	}

	public String postHttp(String url,String params) {
		CloseableHttpClient httpClient=null;
		CloseableHttpResponse httpResponse=null;
		HttpEntity entity=null;
		String result="";
		try {
			httpClient=HttpClients.createDefault();
			HttpPost httpPost=new HttpPost(url);
			httpPost.addHeader("Content-Type", "application/json");
			System.out.println("22222222222");
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                .setSocketTimeout(60000)// 设置读取数据连接超时时间
                .build();
			// 为httpPost实例设置配置
	        httpPost.setConfig(requestConfig);
	        List<NameValuePair> nvps=new ArrayList<NameValuePair>();
	        nvps.add(new BasicNameValuePair("service", "comfirm"));
	        nvps.add(new BasicNameValuePair("urid", "oa"));
	        nvps.add(new BasicNameValuePair("pwd", "oa"));
	        nvps.add(new BasicNameValuePair("parameter", params));
	        httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
	        System.out.println("33333333333333");
	        httpResponse=httpClient.execute(httpPost);
	        System.out.println("444444444444444");
	        entity=httpResponse.getEntity();
	        if (entity!=null) {
	        	System.out.println("55555555555");
	        	System.out.println("entity:"+entity);
	        	 
				result=EntityUtils.toString(entity, "UTF-8");
				logger.info("--------接口返回entity："+result);
			}
	        System.out.println("666666666666666");
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (entity!=null) {
					entity.getContent().close();
				}
			} catch (UnsupportedOperationException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		
		}
		return null;
	}

}
